package cn.wolfcode.service.impl;

import cn.wolfcode.domain.UserInfo;
import cn.wolfcode.mapper.UserInfoMapper;
import cn.wolfcode.redis.RedisKey;
import cn.wolfcode.service.IUserInfoService;
import com.alibaba.fastjson.JSON;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

/**
 * Created by wolfcode-lanxw
 */
@Service
public class UserInfoServiceImpl implements IUserInfoService {
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public UserInfo getUserInfo(Long userId) {
        String key = RedisKey.USER_INFO_STRING.getRealKey(userId.toString());
        String objStr = redisTemplate.opsForValue().get(key);
        UserInfo userInfo = null;
        if(StringUtil.isNullOrEmpty(objStr)){
            userInfo = userInfoMapper.getByUserId(userId);
            if(userInfo!=null){
                redisTemplate.opsForValue().set(key, JSON.toJSONString(userInfo),RedisKey.USER_INFO_STRING.getExpireTime(),RedisKey.USER_INFO_STRING.getUnit());
            }
        }else{
            userInfo = JSON.parseObject(objStr, UserInfo.class);
        }
        return userInfo;
    }

    @Override
    public int update(UserInfo userInfo) {
        return userInfoMapper.update(userInfo);
    }

    @Override
    public void removeUserInfoCache(Long userId) {
        String key = RedisKey.USER_INFO_STRING.getRealKey(userId.toString());
        redisTemplate.delete(key);
    }
}
